/**
 * Generate code from /{{projectName}}-core/src/main/java/{{packageName}}/core/{{modules}}/service/impl/Abstract{{entities@SQL}}Service.java.hbs
 */
package cn.ibizlab.core.ad.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.util.*;
import cn.ibizlab.util.errors.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.core.ad.domain.SysMember;
import cn.ibizlab.core.ad.filter.SysMemberSearchContext;
import cn.ibizlab.core.ad.service.SysMemberService;
import cn.ibizlab.core.ad.mapper.SysMemberMapper;
import cn.ibizlab.util.enums.Entities;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import cn.ibizlab.core.ad.domain.SysOrganizationalRole;
import cn.ibizlab.core.ad.service.SysOrganizationalRoleService;
import cn.ibizlab.core.ad.domain.SysPerson;
import cn.ibizlab.core.ad.service.SysPersonService;
import cn.ibizlab.core.ad.domain.SysActiveDirectory;
import cn.ibizlab.core.ad.service.SysActiveDirectoryService;

/**
 * 实体[成员] 服务对象接口实现
 *
 * @author generator
 */
@Slf4j
public abstract class AbstractSysMemberService extends ServiceImpl<SysMemberMapper,SysMember> implements SysMemberService {

    @Autowired
    @Lazy
    protected SysOrganizationalRoleService sysOrganizationalRoleService;

    @Autowired
    @Lazy
    protected SysPersonService sysPersonService;

    @Autowired
    @Lazy
    protected SysActiveDirectoryService sysActiveDirectoryService;

    @Autowired
    @Lazy
    protected cn.ibizlab.core.ad.mapping.SysMemberInheritMapping sysMemberInheritMapping;

    protected int batchSize = 500;

    public SysMember get(SysMember et) {
        SysMember rt = this.baseMapper.selectEntity(et);
        if(rt == null)
            throw new NotFoundException("数据不存在",Entities.SYS_MEMBER.toString(),et.getId());
        rt.copyTo(et,true);
        return et;
    }

    public List<SysMember> getByEntities(List<SysMember> entities) {
        entities.forEach(et->{
            if(ObjectUtils.isEmpty(et.getId()))
                et.setId((String)et.getDefaultKey(true));
            });
        return this.baseMapper.selectEntities(entities);
    }

    public void fillParentData(SysMember et) {
        if(Entities.SYS_ORGANIZATIONAL_ROLE.equals(et.getContextParentEntity()) && et.getContextParentKey()!=null) {
            et.setOrganizationalRoleId((String)et.getContextParentKey());
            SysOrganizationalRole sysOrganizationalRole = et.getOrganizationalRole();
            if(sysOrganizationalRole == null) {
                sysOrganizationalRole = sysOrganizationalRoleService.getById(et.getOrganizationalRoleId());
                et.setOrganizationalRole(sysOrganizationalRole);
            }
            if(!ObjectUtils.isEmpty(sysOrganizationalRole)) {
                et.setOrganizationalRoleId(sysOrganizationalRole.getId());
                et.setOrganizationalRoleName(sysOrganizationalRole.getName());
                et.setDepartmentId(sysOrganizationalRole.getDepartmentId());
                et.setDepartmentNumber(sysOrganizationalRole.getDepartmentNumber());
                et.setDepartmentName(sysOrganizationalRole.getDepartmentName());
                et.setOrganizationId(sysOrganizationalRole.getOrganizationId());
                et.setOrganizationNumber(sysOrganizationalRole.getOrganizationNumber());
                et.setOrganizationName(sysOrganizationalRole.getOrganizationName());
            }
        }
        if(Entities.SYS_PERSON.equals(et.getContextParentEntity()) && et.getContextParentKey()!=null) {
            et.setPersonId((String)et.getContextParentKey());
            SysPerson sysPerson = et.getPerson();
            if(sysPerson == null) {
                sysPerson = sysPersonService.getById(et.getPersonId());
                et.setPerson(sysPerson);
            }
            if(!ObjectUtils.isEmpty(sysPerson)) {
                et.setPersonId(sysPerson.getId());
                et.setDisplayName(sysPerson.getDisplayName());
                et.setUid(sysPerson.getUid());
                et.setEnabled(sysPerson.getEnabled());
            }
        }
    }

    public SysMember getDraft(SysMember et) {
        fillParentData(et);
        return et;
    }

    public Integer checkKey(SysMember et) {
        if(ObjectUtils.isEmpty(et.getId()))
            et.setId((String)et.getDefaultKey(true));
        return (!ObjectUtils.isEmpty(et.getId()) && this.count(Wrappers.<SysMember>lambdaQuery().eq(SysMember::getId, et.getId()))>0)?1:0;
    }

    @Override
    @Transactional
    public boolean create(SysMember et) {
        fillParentData(et);
        if(ObjectUtils.isEmpty(et.getId()))
            et.setId((String)et.getDefaultKey(true));
        if(this.baseMapper.insert(et) < 1)
            return false;
        get(et);
        return true;
    }

    @Transactional
    public boolean createBatch(List<SysMember> list) {
        list.forEach(et->getSelf().create(et));
        return true;
    }

    @Transactional
    public boolean update(SysMember et) {
        UpdateWrapper<SysMember> qw = et.getUpdateWrapper(true);
        qw.eq("id", et.getId());
        if(!update(et, qw))
            return false;
        get(et);
        return true;
    }

    @Transactional
    public boolean updateBatch(List<SysMember> list) {
        list.forEach(et->getSelf().update(et));
        return true;
    }

    @Override
    @Transactional
    public boolean save(SysMember et) {
        if(checkKey(et) > 0)
            return getSelf().update(et);
        else
            return getSelf().create(et);
    }

    @Transactional
    public boolean saveBatch(List<SysMember> list) {
        if(ObjectUtils.isEmpty(list))
            return true;
        Map<String,SysMember> before = getByEntities(list).stream().collect(Collectors.toMap(SysMember::getId,e->e));
        List<SysMember> create = new ArrayList<>();
        List<SysMember> update = new ArrayList<>();
        list.forEach(sub->{
            if(ObjectUtils.isEmpty(sub.getId()))
                before.values().stream()
                        .filter(e->ObjectUtils.nullSafeEquals(sub.getDefaultKey(true),e.getDefaultKey(true)))
                        .findFirst().ifPresent(e->sub.setId(e.getId()));
            if(!ObjectUtils.isEmpty(sub.getId()) && before.containsKey(sub.getId()))
                update.add(sub);
            else
                create.add(sub);
        });
        if(!update.isEmpty())
            update.forEach(item->this.getSelf().update(item));
        if(!create.isEmpty() && !getSelf().createBatch(create))
            return false;
        else
            return true;
    }

    @Transactional
    public boolean remove(SysMember et) {
        if(!remove(Wrappers.<SysMember>lambdaQuery().eq(SysMember::getId, et.getId())))
            return false;
        return true;
    }

    @Transactional
    public boolean removeByEntities(List<SysMember> entities) {
        for (SysMember et : entities)
            if(!getSelf().remove(et))
                return false;
        return true;
    }

    public Page<SysMember> searchDefault(SysMemberSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<SysMember> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
        List<SysMember> list = pages.getRecords();
        return new PageImpl<>(list, context.getPageable(), pages.getTotal());
    }

    public List<SysMember> listDefault(SysMemberSearchContext context) {
        List<SysMember> list = baseMapper.listDefault(context,context.getSelectCond());
        return list;
    }

    public List<SysMember> findByOrganizationalRoleId(List<String> organizationalRoleIds) {
        List<SysMember> list = baseMapper.findByOrganizationalRoleId(organizationalRoleIds);
        return list;
    }

    public List<SysMember> findByPersonId(List<String> personIds) {
        List<SysMember> list = baseMapper.findByPersonId(personIds);
        return list;
    }

    public boolean removeByOrganizationalRoleId(String organizationalRoleId) {
        List<String> ids = baseMapper.findByOrganizationalRoleId(Arrays.asList(organizationalRoleId)).stream().map(e->e.getId()).collect(Collectors.toList());
        if(!ObjectUtils.isEmpty(ids))
            return this.removeBatch(ids);
        else
            return true;
    }

    public boolean resetByOrganizationalRoleId(String organizationalRoleId) {
        return this.update(Wrappers.<SysMember>lambdaUpdate().eq(SysMember::getOrganizationalRoleId,organizationalRoleId));
    }

    public boolean saveByOrganizationalRole(SysOrganizationalRole sysOrganizationalRole,List<SysMember> list) {
        if(list==null)
            return true;
        Map<String,SysMember> before = findByOrganizationalRoleId(sysOrganizationalRole.getId()).stream().collect(Collectors.toMap(SysMember::getId,e->e));
        List<SysMember> update = new ArrayList<>();
        List<SysMember> create = new ArrayList<>();

        for(SysMember sub:list) {
            sub.setOrganizationalRoleId(sysOrganizationalRole.getId());
            sub.setOrganizationalRole(sysOrganizationalRole);
            if(ObjectUtils.isEmpty(sub.getId()))
                before.values().stream()
                        .filter(e->ObjectUtils.nullSafeEquals(sub.getDefaultKey(true),e.getDefaultKey(true)))
                        .findFirst().ifPresent(e->sub.setId(e.getId()));
            if(!ObjectUtils.isEmpty(sub.getId())&&before.containsKey(sub.getId())) {
                before.remove(sub.getId());
                update.add(sub);
            }
            else
                create.add(sub);
        }
        if(!update.isEmpty())
            update.forEach(item->this.getSelf().update(item));
        if(!create.isEmpty() && !getSelf().createBatch(create))
            return false;
        else if(!before.isEmpty() && !getSelf().removeBatch(before.keySet()))
            return false;
        else
            return true;
    }

    public boolean removeByPersonId(String personId) {
        List<String> ids = baseMapper.findByPersonId(Arrays.asList(personId)).stream().map(e->e.getId()).collect(Collectors.toList());
        if(!ObjectUtils.isEmpty(ids))
            return this.removeBatch(ids);
        else
            return true;
    }

    public boolean resetByPersonId(String personId) {
        return this.update(Wrappers.<SysMember>lambdaUpdate().eq(SysMember::getPersonId,personId));
    }

    public boolean saveByPerson(SysPerson sysPerson,List<SysMember> list) {
        if(list==null)
            return true;
        Map<String,SysMember> before = findByPersonId(sysPerson.getId()).stream().collect(Collectors.toMap(SysMember::getId,e->e));
        List<SysMember> update = new ArrayList<>();
        List<SysMember> create = new ArrayList<>();

        for(SysMember sub:list) {
            sub.setPersonId(sysPerson.getId());
            sub.setPerson(sysPerson);
            if(ObjectUtils.isEmpty(sub.getId()))
                before.values().stream()
                        .filter(e->ObjectUtils.nullSafeEquals(sub.getDefaultKey(true),e.getDefaultKey(true)))
                        .findFirst().ifPresent(e->sub.setId(e.getId()));
            if(!ObjectUtils.isEmpty(sub.getId())&&before.containsKey(sub.getId())) {
                before.remove(sub.getId());
                update.add(sub);
            }
            else
                create.add(sub);
        }
        if(!update.isEmpty())
            update.forEach(item->this.getSelf().update(item));
        if(!create.isEmpty() && !getSelf().createBatch(create))
            return false;
        else if(!before.isEmpty() && !getSelf().removeBatch(before.keySet()))
            return false;
        else
            return true;
    }

    @Override
    public List<JSONObject> select(String sql, Map param){
        return this.baseMapper.selectBySQL(sql,param);
    }

    @Override
    @Transactional
    public boolean execute(String sql , Map param){
        if (sql == null || sql.isEmpty()) {
            return false;
        }
        if (sql.toLowerCase().trim().startsWith(SqlMethod.INSERT_ONE.getMethod())) {
            return this.baseMapper.insertBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith(SqlMethod.UPDATE.getMethod())) {
            return this.baseMapper.updateBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith(SqlMethod.DELETE.getMethod())) {
            return this.baseMapper.deleteBySQL(sql,param);
        }
        log.warn("暂未支持的SQL语法");
        return true;
    }

    @Override
    protected Class currentMapperClass() {
        return SysMemberMapper.class;
    }

    @Override
    protected Class currentModelClass() {
        return SysMember.class;
    }
}